<template>
  <div class="app-container">
    <el-card :bordered="false">
      <el-form  ref="formValidate" :rules="ruleValidate" :model="formValidate" label-width="130px" >
        <el-row :gutter="24">
          <!-- 商品信息-->
          <el-col v-bind="grid2">
            <el-form-item label="商户名称：" prop="store_name">
              <el-input v-model="formValidate.store_name" placeholder="请输入商户名称"  />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="商户分类：" prop="cate_id">
              <el-select v-model="formValidate.cate_id" filterable :filter-method="dataFilter" clearable>
                <el-option v-for="item in optionsMetaShow" :disabled="item.disabled === 0"
                :value="item.value" :key="item.id" :label="item.label" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="商户关键字：" prop="">
              <el-input v-model="formValidate.keyword" placeholder="请输入商户关键字"  />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="单位：" prop="unit_name">
              <el-input v-model="formValidate.unit_name"  placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="商户简介：" prop="">
              <el-input v-model="formValidate.store_info" type="textarea" :rows="3" placeholder="请输入商品简介" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商户封面图：" prop="image">
              <single-pic v-model="formValidate.image"  type="image" :num="1" :width="150" :height="150" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商户轮播图：" prop="slider_image">
              <MaterialList v-model="formValidate.slider_image"  type="image" :num="4" :width="150" :height="150" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品详情：">
              <ueditor-wrap v-model="formValidate.description" :config="myConfig"  @beforeInit="addCustomDialog"  style="width: 90%;"></ueditor-wrap>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-bind="grid">
            <el-form-item label="商品状态：">
              <el-radio-group v-model="formValidate.is_show" >
                <el-radio :label="1" class="radio">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="地图：">
                <div id="container" style="width: 720px; height: 300px;"></div>
                    <div id="searchPart">
                    <el-input size="mini" style="width: 720px;" v-model="area"  type="text" id="searchInput" placeholder="请输入" />
                    <el-button type="primary" size="mini" id="searchBtn" @click="handle_search">搜索</el-button>
                </div>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="经纬度："><span id="position" >{{lat}} {{lng}}</span></el-form-item>
          </el-col>
        </el-row>
        <el-row>
            <el-col>
              <el-form-item label="区域：">
                  <el-cascader :props="props"></el-cascader>
              </el-form-item>
            </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" class="submission" @click="handleSubmit('formValidate')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
   
  </div>
</template>

<script>
import { getCates } from "@/api/yxStoreCategory";
import {
  add,
  edit,
  getInfo,
  isFormatAttr,
  addShop,
  getArea,
} from "@/api/yxStoreProduct";
import editor from "../../components/Editor";
import picUpload from "@/components/pic-upload";
import mulpicUpload from "@/components/mul-pic-upload";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MaterialList from "@/components/material";
import singlePic from "@/components/singlematerial";
import UeditorWrap from "vue-ueditor-wrap";
import $ from "jquery";
export default {
  components: {
    editor,
    picUpload,
    mulpicUpload,
    Treeselect,
    MaterialList,
    UeditorWrap,
    singlePic,
  },
  data() {
    return {
      spinShow: false,
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24,
      },
      grid3: {
        xl: 18,
        lg: 18,
        md: 20,
        sm: 24,
        xs: 24,
      },
      // 批量设置表格data
      oneFormBatch: [
        {
          pic: "",
          price: 0,
          cost: 0,
          ot_price: 0,
          stock: 0,
          bar_code: "",
          seckill_stock: 0,
          seckill_price: 0,
          pink_stock: 0,
          pink_price: 0,
          weight: 0,
          volume: 0,
        },
      ],
      // 规格数据
      formDynamic: {
        attrsName: "",
        attrsVal: "",
      },
      formDynamicNameData: [],
      isBtn: false,
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: "100%", // 初始容器宽度
        UEDITOR_HOME_URL: "/UEditor/",
        serverUrl: "",
      },
      columns: [],
      formValidate: {
        imageArr: [],
        sliderImageArr: [],
        store_name: "",
        cate_id: "",
        keyword: "",
        unit_name: "",
        store_info: "",
        image: "",
        slider_image: [],
        description: "",
        ficti: 0,
        give_integral: 0,
        sort: 0,
        is_show: 1,
        is_hot: 0,
        is_benefit: 0,
        is_best: 0,
        is_new: 0,
        is_good: 0,
        is_postage: 0,
        is_sub: 0,
        id: 0,
        spec_type: 0,
        temp_id: "",
        attrs: [],
        items: [
          {
            pic: "",
            price: 0,
            cost: 0,
            ot_price: 0,
            stock: 0,
            bar_code: "",
          },
        ],
        header: [],
        selectRule: "",
      },
      ruleList: [],
      templateList: [],
      createBnt: false,
      showIput: false,
      manyFormValidate: [],
      // 单规格表格data
      oneFormValidate: [
        {
          imageArr: [],
          pic: "",
          price: 2,
          cost: 0,
          ot_price: 0,
          stock: 0,
          seckill_stock: 0,
          seckill_price: 0,
          pink_stock: 0,
          pink_price: 0,
          bar_code: "",
          weight: 0,
          volume: 0,
          brokerage: 0,
          brokerage_two: 0,
        },
      ],
      images: [],
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      },
      loading: false,
      treeSelect: [],
      optionsMetaShow: [],
      tableIndex: 0,
      ruleValidate: {
        store_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        cate_id: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
        keyword: [
          { required: true, message: "请输入商品关键字", trigger: "blur" },
        ],
        unit_name: [{ required: true, message: "请输入单位", trigger: "blur" }],
        store_info: [
          { required: true, message: "请输入商品简介", trigger: "blur" },
        ],
        spec_type: [
          { required: true, message: "请选择商品规格", trigger: "change" },
        ],
        selectRule: [
          { required: true, message: "请选择商品规格属性", trigger: "change" },
        ],
        temp_id: [
          {
            required: true,
            message: "请选择运费模板",
            trigger: "change",
            type: "number",
          },
        ],
      },
      attrs: [],
      area: "",
      lat: "",
      lng: "",
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          getArea({
            parentCode: "",
            level: "",
          }).then(res => {
            console.log(res);
            debugger;

            let nodes = res.map((item, index) => {
              return {
                value: item.parentCode,
                label: item.name,
                lvl: item.level,
              };
            });
            resolve(nodes);

            // resolve(nodes);
            // const nodes = Array.from({ length: level + 1 })
            // .map(item => ({
            //   value: ++id,
            //   label: `选项${id}`,
            //   leaf: level >= 2
            // }));
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            // resolve(nodes);
          });
        },
      },
    };
  },
  watch: {
    "formValidate.image": function(val) {
      console.log("aaaa:" + val);
      if (val) {
        this.oneFormValidate[0].pic = val;
        console.log("bbbbbb:" + this.oneFormValidate.pic);
      }
    },
    "form.sliderImageArr": function(val) {
      if (val) {
        this.form.slider_image = val.join(",");
      }
    },
  },
  mounted() {
    this.getInfo();
  },
  methods: {
    dataFilter(val) {
      this.value = val;
      if (val) {
        this.optionsMetaShow = this.treeSelect.filter(item => {
          if (
            !!~item.label.indexOf(val) ||
            !!~item.label.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        this.optionsMetaShow = this.treeSelect;
      }
    },
    confirm() {
      let that = this;
      that.createBnt = true;
      if (that.formValidate.selectRule.trim().length <= 0) {
        return this.$message({
          message: "请选择属性",
          type: "error",
        });
      }
      that.ruleList.forEach(function(item, index) {
        if (item.ruleName === that.formValidate.selectRule) {
          that.attrs = item.ruleValue;
        }
      });
    },
    // 删除表格中的属性
    delAttrTable(index) {
      this.manyFormValidate.splice(index, 1);
    },

    // 添加按钮
    addBtn() {
      this.clearAttr();
      this.createBnt = false;
      this.showIput = true;
    },
    // 立即生成
    generate() {
      isFormatAttr(this.formValidate.id, { attrs: this.attrs })
        .then(res => {
          this.manyFormValidate = res.value;
          let headerdel = {
            title: "操作",
            slot: "action",
            fixed: "right",
            width: 220,
          };
          res.header.push(headerdel);
          this.formValidate.header = res.header;
          //this.formValidate.attrs = res.attr;
          let header = res.header;
          header.pop();
          if (!this.$route.params.id && this.formValidate.spec_type === 1) {
            this.manyFormValidate.map(item => {
              item.pic = this.formValidate.image;
            });
            this.oneFormBatch[0].pic = this.formValidate.image;
          }
        })
        .catch(res => {
          // this.$message({
          //   message:res.msg,
          //   type: 'error'
          // });
        });
    },
    // 取消
    offAttrName() {
      this.showIput = false;
      this.createBnt = true;
    },
    clearAttr() {
      this.formDynamic.attrsName = "";
      this.formDynamic.attrsVal = "";
    },
    // 删除规格
    handleRemoveRole(index) {
      this.attrs.splice(index, 1);
      this.manyFormValidate.splice(index, 1);
    },
    // 删除属性
    handleRemove2(item, index) {
      item.splice(index, 1);
    },
    // 添加规则名称
    createAttrName() {
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        let data = {
          value: this.formDynamic.attrsName,
          detail: [this.formDynamic.attrsVal],
        };
        this.attrs.push(data);
        var hash = {};
        this.attrs = this.attrs.reduce(function(item, next) {
          hash[next.value] ? "" : (hash[next.value] = true && item.push(next));
          return item;
        }, []);
        this.clearAttr();
        this.showIput = false;
        this.createBnt = true;
      } else {
        this.$message.warning("请添加完整的规格！");
      }
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.attrs[idx].detail.push(num);
        var hash = {};
        this.attrs[idx].detail = this.attrs[idx].detail.reduce(function(
          item,
          next
        ) {
          hash[next] ? "" : (hash[next] = true && item.push(next));
          return item;
        },
        []);
      } else {
        this.$message.warning("请添加属性！");
      }
    },

    // 改变规格
    changeSpec() {},
    // 详情
    getInfo() {
      let that = this;
      let id = that.$route.params.id || 0;
      getInfo(id)
        .then(res => {
          let data = res.productInfo;
          console.log("data:" + data);
          if (data) {
            let cate_id = parseInt(data.cate_id) || 0;
            this.attrs = data.items || [];
            that.formValidate = data;
            that.formValidate.cate_id = cate_id;
            that.oneFormValidate = [data.attr];
            that.formValidate.header = [];
            that.generate();
            that.manyFormValidate = data.attrs;
            if (data.spec_type === 0) {
              that.manyFormValidate = [];
            } else {
              that.createBnt = true;
              that.oneFormValidate = [
                {
                  pic: "",
                  price: 0,
                  cost: 0,
                  ot_price: 0,
                  stock: 0,
                  seckill_stock: 0,
                  seckill_price: 0,
                  pink_stock: 0,
                  pink_price: 0,
                  bar_code: "",
                  weight: 0,
                  volume: 0,
                  brokerage: 0,
                  brokerage_two: 0,
                },
              ];
            }
          }

          that.treeSelect = res.cateList;
          that.ruleList = res.ruleList;
          that.templateList = res.tempList;
          that.optionsMetaShow = that.treeSelect;
        })
        .catch(res => {
          console.log("err:" + res);
          return this.$message({
            message: res.msg,
            type: "error",
          });
        });
      that.initMap();
    },
    initMap() {
      var that = this;
      // var position = document.getElementById("position");

      var center = new TMap.LatLng(39.984104, 116.307503); //设置中心点坐标
      //初始化地图
      var map = new TMap.Map("container", {
        center: center,
      });
      //绑定点击事件
      map.on("click", function(evt) {
        that.lat = evt.latLng.getLat().toFixed(6);
        that.lng = evt.latLng.getLng().toFixed(6);
        // position.innerHTML = lat + "," + lng;
      });
    },
    handle_search() {
      var that = this;
      debugger;
      $.ajax({
        type: "get",
        dataType: "jsonp",
        data: {
          key: "G36BZ-CFXRS-WF4OL-6BE3X-6756F-UUBMF", // 填申请到的key
          address: encodeURI(that.area), //具体的地址
          output: "jsonp", //返回格式：支持JSON/JSONP，默认JSON
        },
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: "https://apis.map.qq.com/ws/geocoder/v1/?",
        success: function(json) {
          if (json.status == 0) {
            that.lat = json.result.location.lat;
            that.lng = json.result.location.lng;
            // console.log('经度：', lat);
            // console.log('纬度：', lng);
          } else {
            console.log("错误信息：", json.message);
          }
        },
        error: function(err) {
          console.log("异常错误，请刷新浏览器后重试");
        },
      });

      // let script = document.createElement('script');
      // let url =
      // script.src = url;
      // document.body.appendChild(script);
    },
    // 提交
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.formValidate.spec_type === 0) {
            this.formValidate.attrs = this.oneFormValidate;
            this.formValidate.header = [];
            this.formValidate.items = [];
          } else {
            this.formValidate.items = this.attrs;
            this.formValidate.attrs = this.manyFormValidate;
          }
          if (
            this.formValidate.spec_type === 1 &&
            this.manyFormValidate.length === 0
          ) {
            return this.$message.warning("请点击生成规格！");
          }
          addShop(this.formValidate)
            .then(async res => {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              setTimeout(() => {
                this.$router.push({ path: "/shop/goods" });
              }, 500);
            })
            .catch(res => {
              // this.$message({
              //   message:res.message,
              //   type: 'error'
              // });
            });
        } else {
          if (
            !this.formValidate.store_name ||
            !this.formValidate.cate_id ||
            !this.formValidate.keyword ||
            !this.formValidate.unit_name ||
            !this.formValidate.store_info ||
            !this.formValidate.image ||
            !this.formValidate.slider_image
          ) {
            this.$message.warning("请填写完整商品信息！");
          }
        }
      });
    },

    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$message.warning(error);
      }
    },
    addCustomDialog() {
      window.UE.registerUI(
        "yshop",
        function(editor, uiName) {
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: "/yshop/materia/index",
            editor: editor,
            name: uiName,
            title: "上传图片",
            cssRules: "width:1200px;height:500px;padding:20px;",
          });
          this.dialog = dialog;

          var btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function() {
              dialog.render();
              dialog.open();
            },
          });

          return btn;
        },
        37
      );
    },

    cancel() {
      this.resetForm();
    },
  },
};
</script>

<style scoped lang="stylus">
.submission {
  margin-left: 10px;
}

.color-list .tip {
  color: #c9c9c9;
}

.color-list .color-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #fff;
  margin-right: 10px;
}

.color-list .color-item.blue {
  background-color: #1E9FFF;
}

.color-list .color-item.yellow {
  background-color: rgb(254, 185, 0);
}

.color-list .color-item.green {
  background-color: #009688;
}

.columnsBox {
  margin-right: 10px;
}

.priceBox {
  width: 100%;
}

.rulesBox {
  display: flex;
  flex-wrap: wrap;
}

.curs {
  cursor: pointer;
}
</style>
